package com.tecso.btx.admin.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

import com.tecso.btx.admin.dao.IGenericDao;


public abstract class GenericDaoJpaImpl<T, PK extends Serializable> implements IGenericDao<T, PK> {

	/*
	 * 
	 */

	protected Class<T> entityClass;

	@PersistenceContext 
	protected EntityManager entityManager;

	
	@SuppressWarnings("unchecked")
	public GenericDaoJpaImpl() {
		ParameterizedType genericSuperclass = (ParameterizedType) getClass()
				.getGenericSuperclass();
		this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
	}

	@Override
	@Transactional
	public T create(T t) {
		this.entityManager.persist(t);
		return t;
	}

	@Override
	public T read(PK id) {
		return this.entityManager.find(entityClass, id);
	}

	@Override
	@Transactional
	public T update(T t) {
		return this.entityManager.merge(t);
	}

	@Override
	@Transactional
	public void delete(T t) {

		t = this.entityManager.merge(t);
		this.entityManager.remove(t);

	}

	
	
	@SuppressWarnings("unchecked")
	public List<T> getAll() {
		return entityManager.createQuery(
				"Select t from " + entityClass.getSimpleName() + " t").getResultList();
	}

	

	public EntityManager getEntityManager() {
		return entityManager;
	}
	
}
